﻿using Newtonsoft.Json;

namespace PmSoft.Web.Abstractions.Settings;

public class DateTimeJsonConverter : JsonConverter<DateTime>
{
    //public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    //{
    //    if (reader.TokenType == JsonTokenType.String)
    //    {
    //        if (DateTime.TryParse(reader.GetString(), out DateTime value))
    //            return value;
    //    }
    //    return reader.GetDateTime();
    //}

    //public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    //{
    //    if (value.Hour == 0 && value.Minute == 0 && value.Second == 0)
    //    {
    //        writer.WriteStringValue(value.ToString("yyyy-MM-dd"));
    //    }
    //    else
    //    {
    //        writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
    //    }
    //}
    public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.String)
        {
            var stringValue = (string)reader.Value;
            if (DateTime.TryParse(stringValue, out DateTime value))
            {
                return value;
            }
        }
        throw new InvalidOperationException("Invalid date format.");
    }

    public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
    {
        if (value.Hour == 0 && value.Minute == 0 && value.Second == 0)
        {
            writer.WriteValue(value.ToString("yyyy-MM-dd"));
        }
        else
        {
            writer.WriteValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
public class DateTimeNullJsonConverter : JsonConverter<DateTime?>
{

    public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        //if (!existingValue.HasValue) return null;
        if (reader.TokenType == JsonToken.String)
        {
            var stringValue = (string)reader.Value;
            if (DateTime.TryParse(stringValue, out DateTime value))
            {
                return value;
            }
        }
        return null;
    }

    public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
    {
        if (!value.HasValue) return;
        if (value.Value.Hour == 0 && value.Value.Minute == 0 && value.Value.Second == 0)
        {
            writer.WriteValue(value.Value.ToString("yyyy-MM-dd"));
        }
        else
        {
            writer.WriteValue(value.Value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}